/*
 * To change this template, choose Tools | Templates and open the template in
 * the editor.
 */
package org.afraid.poison.common;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;

public final class LRUCache<K, V> {

	private static final float LOAD_FACTOR=0.75f;
	private final Map<K, V> map;
	private final int cacheSize;

	public LRUCache(int cacheSize) {
		this.cacheSize=cacheSize;
		int hashTableCapacity=(int) Math.ceil(cacheSize/LOAD_FACTOR)+1;
		map=Collections.synchronizedMap(new LinkedHashMap<K, V>(hashTableCapacity, LOAD_FACTOR, true) {

			private static final long serialVersionUID=1;

			@Override
			protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
				return size()>LRUCache.this.cacheSize;
			}
		});
	}

	public V get(K key) {
		return map.get(key);
	}

	public void put(K key, V value) {
		map.put(key, value);
	}

	public void clear() {
		map.clear();
	}

	public V remove(K key) {
		return map.remove(key);
	}

	public int size() {
		return map.size();
	}

	public synchronized Collection<Map.Entry<K, V>> getAll() {
		return new ArrayList<Map.Entry<K, V>>(map.entrySet());
	}
}
